package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.ververica.cdc.connectors.mysql.MySQLSource;
import com.alibaba.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.alibaba.ververica.cdc.debezium.DebeziumSourceFunction;
import com.atguigu.gmall.realtime.app.func.DimSink;
import com.atguigu.gmall.realtime.app.func.MyDeserializationSchema;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;

/**
 * Author: Felix
 * Date: 2022/1/15
 * Desc: 业务数据动态分流
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、hbase、BaseDBApp
 * 执行流程
 *      -基本环境准备
 *      -检查点设置
 *      -读取主流中业务数据
 *      -对读取的数据进行类型转换
 *      -对主流业务数据进行ETL
 *
 *      -使用FlinkCDC读取配置表中的数据，得到配置流
 *      -将配置流进行广播，并创建广播状态
 *      -使用connect算子将主流和配置流进行连接
 *      -对连接之后的流进行分流处理  ---维度数据：维度侧输出流中     事实数据：主流
 *
 *      -抽取TableProcessFunction类处理分流业务
 *          >processElement
 *              4.字段过滤
 *              2.从状态中获取当前处理的业务数据对应的配置信息，根据配置信息进行分流
 *          >processBroadcastElement
 *              1.从广播流中读取配置信息封装为TableProcess对象，并放到广播状态中
 *              3.如果当前读到的配置信息是维度配置的话，提前创建维度表
 *                  -抽取专门建表的方法 checkTable
 *                  -拼接建表语句
 *                  -通过jdbc方式 执行建表语句
 *
 *
 */
public class BaseDBApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 并行度设置
        env.setParallelism(4);
        //TODO 2.检查点相关设置(略)
        //TODO 3.从Kafka中读取业务数据
        //3.1 声明消费的主题以及消费者组
        String topic = "ods_base_db_m";
        String groupId = "base_db_app_group";
        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaDS = env.addSource(kafkaSource);

        //TODO 4.对读取的数据进行类型转换  jsonStr -->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //TODO 5.对读取到的数据进行简单的ETL清洗
        SingleOutputStreamOperator<JSONObject> filterDS = jsonObjDS.filter(
            new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject jsonObj) throws Exception {
                    boolean flag =
                        jsonObj.getString("table") != null &&
                            jsonObj.getString("table").length() > 0 &&
                            jsonObj.getJSONObject("data") != null &&
                            jsonObj.getString("data").length() > 3;
                    return flag;
                }
            }
        );

        //filterDS.print(">>>");
        //TODO 6.使用FlinkCDC读取配置表数据--封装为流
        //6.1 创建MySQLSourceFunction
        DebeziumSourceFunction<String> sourceFunction = MySQLSource.<String>builder()
            .hostname("hadoop202")
            .port(3306)
            .databaseList("gmall0722_realtime")
            .tableList("gmall0722_realtime.table_process")
            .username("root")
            .password("123456")
            .startupOptions(StartupOptions.initial())
            .deserializer(new MyDeserializationSchema())
            .build();
        //6.2 读取数据  封装为流
        DataStreamSource<String> mySQLDS = env.addSource(sourceFunction);

        //TODO 7.将配置流进行广播--定义广播状态
        MapStateDescriptor<String, TableProcess> mapStateDescriptor =
            new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);
        BroadcastStream<String> broadcastDS = mySQLDS.broadcast(mapStateDescriptor);

        //TODO 8.使用connect将两条流连接在一起
        BroadcastConnectedStream<JSONObject, String> connectDS = filterDS.connect(broadcastDS);

        //TODO 9.动态分流--分别处理两条流中的数据   事实--主流     维度--侧输出流
        OutputTag<JSONObject> dimTag = new OutputTag<JSONObject>("dimTag"){};
        SingleOutputStreamOperator<JSONObject> realDS = connectDS.process(new TableProcessFunction(dimTag,mapStateDescriptor));

        DataStream<JSONObject> dimDS = realDS.getSideOutput(dimTag);

        realDS.print(">>>");
        dimDS.print("###");

        //TODO 10.将维度侧输出流的数据写到phoenix维度表中
        dimDS.addSink(new DimSink());

        //TODO 11.将主流事实数据写到kafka主题中
        realDS.addSink(
            MyKafkaUtil.getKafkaSinkBySchema(
                new KafkaSerializationSchema<JSONObject>() {
                    @Override
                    public ProducerRecord<byte[], byte[]> serialize(JSONObject jsonObj, @Nullable Long timestamp) {
                        String topic = jsonObj.getString("sink_table");
                        return new ProducerRecord<byte[], byte[]>(topic,jsonObj.getJSONObject("data").toJSONString().getBytes());
                    }
                }
            )
        );

        env.execute();
    }
}
